<template>
  <div>
    <van-nav-bar title="附近的充电站" left-text="返回" left-arrow @click-left="onClickLeft"/>
    <!-- 新增搜索框 -->
    <div>
      <el-input
          id="search-input"
          type="text"
          v-model="searchText"
          placeholder="请输入关键字搜索地点"
          @blur="search"
          style="width: 100%;"
          clearable
          @focus="clearSearchDIV()"
      />
      <div id="search-result-panel"></div>  <!-- 用于展示搜索结果的容器 -->
    </div> <!-- 添加这个元素用于展示搜索结果 -->
  </div>
  <div style="margin: 8px 8px 20px 8px">
    <div id="container" style="margin-top: 30px;height: 50vh;position: absolute;z-index: 1"></div>
    <el-button
        style="position: absolute;right: 100px;top: 80px;" type="primary" @click="dialogVisible = true">打开导航
    </el-button> <!-- 添加这个元素用于展示搜索结果-->
    <el-button
        style="position: absolute;right: 1px;top: 80px;" type="danger" @click="closeNavigator()">关闭导航
    </el-button>
    <div id="my-panel-luxian" style="display: none"></div>
  </div>

  <!-- 改进导航 -->
  <el-dialog
      v-model="dialogVisible"
      width="350"
      style="height: 430px;"
  >
    <div class="search-container">
        <label>输入导航的目的地:</label>
        <el-input 
            type="text" 
            v-model="searchForm.navigatorName"
            @input="handleSearchInput"
            @focus="isShowSearchHistory()"
        />
        <!-- 添加搜索历史下拉列表 -->
        <div v-show="showSearchHistory" class="search-history">
            <div 
                v-for="(item, index) in filteredHistory" 
                :key="index" 
                class="history-item"
                @click="selectHistory(item)"
            >
                {{ item.navigatorName }}
            </div>
            <div v-if="filteredHistory.length === 0" class="no-results">
                无搜索记录
            </div>
        </div>
    </div>
    <el-button type="primary" @click="toDestination()" 
    style="position: absolute;bottom: 10px;width: 320px;">导航</el-button>
  </el-dialog>
</template>

<script setup>
import {onMounted, onUnmounted} from "vue";
import {ref} from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import {showFailToast} from 'vant';
import {insertNavigatorJs, navigationListJs, selectNavigatorJs} from "@/api/core";

let map = null;
let toolbar = null;
let scale = null;
let mapType = null;
let placeSearch = null;
let driving = null;

// 定义要查询的表单
const searchForm = ref({
  navigatorName: null
})

// 当前我的坐标
const longitude = ref(116.461841);
const latitude = ref(39.909104);
// 搜索变量
const searchText = ref("");

const onClickLeft = () => history.back();

function initAMap() {
  window._AMapSecurityConfig = {
    securityJsCode: "f15d8560e8fb7ca2efd9d791cd391d30",
  };
}

// 导航
const dialogVisible = ref(false)

// 渲染地图方法
onMounted(() => {
  setTimeout(() => {
   // getLocationByIP();
    initAMap();
    console.info(longitude.value);
    console.info(latitude.value);
    AMapLoader.load({
      key: "8034ae7b9e3fc5876528f75e678bd259", // 申请好的Web端开发者Key，首次调用 load 时必填
      version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: [], // 需要使用的的插件列表，如比例尺'AMap.Scale'等,
    })
        .then((AMap) => {
          map = new AMap.Map("container", {
            // 设置地图容器id
            viewMode: "3D", // 是否为3D地图模式
            zoom: 11, // 初始化地图级别
            center: [longitude.value, latitude.value], // 初始化地图中心点位置 TODO 添加自已的经纬度 显示点
          });
          // 添加地图组件
          //异步加载控件
          // 定义一个数组来存放需要加载的插件名称
          const pluginsToLoad = ['AMap.ToolBar', 'AMap.Scale', 'AMap.MapType'];  // 这里添加了你想要的多个插件，可按需继续添加其他插件名称
          AMap.plugin(pluginsToLoad, function () {
            // 实例化每个插件对应的组件
            toolbar = new AMap.ToolBar();
            scale = new AMap.Scale();
            mapType = new AMap.MapType();
            // 依次将各个组件添加到地图上
            map.addControl(toolbar);
            map.addControl(scale);
            map.addControl(mapType);
          });
          toolbar.show(); //缩放工具展示
          scale.show();
          mapType.show();
          // 添加点标记
          //点标记显示内容
          const markerContent = `<div class="">
              <img src="https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png">
              <div class="close-btn" onclick="clearMarker()">你的位置</div>
              </div>`;
          const marker = new AMap.Marker({
            position: new AMap.LngLat(longitude.value, latitude.value), //点标记的位置 TODO: 添加自已的经纬度 显示点标记
            offset: new AMap.Pixel(-13, -30), //偏移量
            content: markerContent, //添加 Icon 实例
            title: "个人",
            zooms: [2, 105], //点标记显示的层级范围，超过范围不显示
          });
          map.add(marker);
          // 搜索
          initPlaceSearch(AMap);
          // 规划路线 // TODO: 添加自已的经纬度  根据数据库中的经纬度做结束点 显示路线
          /*var p1 = [116.461841, 39.909104]; // TODO: 添加自已的经纬度 做计算 显示距离
          var p2 = [116.414667, 39.896948];
          //返回 p1 到 p2 间的地面距离，单位：米
          var dis = AMap.GeometryUtil.distance(p1, p2);
          var count = (dis / 1000).toFixed(2)
          console.log(dis, "计算结果")
          console.log(count, "计算结果--公里")*/
          //引入和创建驾车规划插件
          function getNavigator(startLngLat, endLngLat) {
            try {
              console.log(AMap, "--------------")
              AMap.plugin("AMap.Driving", function () {
                driving = new AMap.Driving({
                  map: map,
                  panel: "my-panel-luxian", //参数值为你页面定义容器的 id 值<div id="my-panel"></div>
                });
                //获取起终点规划线路
                driving.search(startLngLat, endLngLat, function (status, result) {
                  try {
                    if (status === "complete") {
                      //status：complete 表示查询成功，no_data 为查询无结果，error 代表查询错误
                      //查询成功时，result 即为对应的驾车导航信息
                      console.log(result);
                    } else {
                      console.log("获取驾车数据失败：" + result);
                    }
                  } catch (innerError) {
                    console.error("在处理驾车查询结果时出现错误：", innerError);
                    // 这里可以添加更多逻辑，比如向用户显示一个友好的提示框告知出现了内部错误等
                  }
                });
              });
            } catch (error) {
              console.error("在初始化驾车导航或者进行查询操作时出现错误：", error);
            }
          }
          window.getNavigator = getNavigator;
          // getNavigator(AMap, startLngLat, endLngLat);

        })
  }, 1000)
})

onUnmounted(() => {
  map?.destroy();
});


function toDestination() {
  // 先查询要导航路线
  selectNavigatorJs(searchForm.value).then(res => {
    const startLngLat = [longitude.value, latitude.value] //起始点坐标
    if (res.data.code == 200000) {
      console.log(res.data.data)
      const endLngLat = [res.data.data.navigatorLongitude, res.data.data.navigatorLatitude] //终点坐标  默认先给 0*/
      dialogVisible.value = false
      if(typeof window.getNavigator === 'function'){
        console.log(111)
        window.getNavigator(startLngLat, endLngLat)
        const element = document.getElementById('my-panel-luxian');
        element.style.display = 'block';
      }else{
        console.log("函数没有初始化完成")
      }
    }
  })
}


//这个获取方式不是很准确
//可以参考官网进行优化
// https://lbs.amap.com/api/javascript-api-v2/prerequisites
/*function getLocationByIP() {
  try {
    const request = axios.create({
      baseURL: "https://ipapi.co",
      timeout: 10000
    });
    request.get('/json/')
        .then(response => {
          const data = response.data;
          console.log(data); // 这里可以访问到返回的数据
          longitude.value = response.data.longitude;
          latitude.value = response.data.latitude;
        })
        .catch(error => {
          console.error("Error fetching data:", error);
        });
  } catch (error) {
    showFailToast('获取用户当前经纬度失败');
  }
}*/

// 初始化搜索
const initPlaceSearch = (AMap) => {
  return new Promise((resolve, reject) => {
    AMap.plugin(["AMap.PlaceSearch"], function () {
      placeSearch = new AMap.PlaceSearch({
        pageSize: 5,
        pageIndex: 1,
        city: "010",
        citylimit: true,
        map: map,
        panel: "search-result-panel", // 修改为新的结果展示容器id
        autoFitView: true,
      });
      resolve();
    }).catch((e) => {
      reject(e);
    });
  });
}

// 搜索方法
const search = async () => {
  const element = document.getElementById('search-result-panel');
  element.style.display = 'block';
  const keyword = searchText.value;
  if (keyword) {
    try {
      if (!placeSearch) {
        await initPlaceSearch();
        console.log('placeSearch已初始化：', placeSearch); // 添加这行打印，查看初始化情况
      }
      // TODO: 添加自已的经纬度 显示搜索结果
      var cpoint = [116.461841, 39.909104]; // 自身所在经纬度
      placeSearch.searchNearBy(keyword, cpoint, 1000, function (status, result) {
        console.log(result, "----------result");
        console.log(status, "----------status");
        if (status === 'complete' && result.info === 'OK') {
          console.log(result.poiList.pois);
          const insertNavigators = ref([])
          result.poiList.pois.forEach(el => {
            const form = ref({
              navigatorName: null,
              navigatorLongitude: null,
              navigatorLatitude: null
            })
            console.log(el.name)
            console.log(el.location.lat)
            console.log(el.location.lng)
            form.value.navigatorName = el.name
            form.value.navigatorLatitude = el.location.lat
            form.value.navigatorLongitude = el.location.lng
            insertNavigators.value.push(form.value)
          });
          console.log(insertNavigators.value)
          insertNavigatorJs(insertNavigators.value).then(res => {
            if (res.data.code == 200000) {
              console.log("添加成功")
            }
          })
        } else {
          console.error('搜索出现问题，状态：', status, '，详细信息：', result);
        }
      });
    } catch (error) {
      console.error('搜索附近信息出错：', error);
      showFailToast('搜索附近信息失败');
    }
  }
};

// 清除下拉框
function clearSearchDIV() {
  document.getElementById('search-result-panel').style.display = 'none';
}


function closeNavigator() {
  document.getElementById('my-panel-luxian').style.display = 'none';
}

// 下拉列表展示
const filteredHistory = ref([])

const showSearchHistory = ref(false)
function isShowSearchHistory(){
  showSearchHistory.value = true
  if(showSearchHistory.value){
  getNavigationList()
}
}

// 获取导航历史
const getNavigationList = () => {
  navigationListJs().then(res => {
    filteredHistory.value = res.data.data
  })
}

// 下拉列表点击
function selectHistory(item){
  searchForm.value.navigatorName = item.navigatorName
}


</script>

<style scoped>
#container {
  width: 100%;
  height: 350px;
}

.custom-content-marker img {
  width: 100%;
  height: 100%;
}

.component-window button {
  padding: 4px 8px;
  border: none;
  background-color: #f5f5f5;
  cursor: pointer;
}

#search-result-panel {
  width: 300px;
  height: 400px;
  overflow-y: auto;
  border: 1px solid #ccc;
  background-color: white;
  margin-top: 8px;
}

#my-panel-luxian {
  width: 100%;
  height: 300px;
  overflow-y: auto;
  border: 1px solid #ccc;
  background-color: white;
  margin-bottom: 8px;
  position: absolute;
  bottom: 40px;
  z-index: 2;
}

.component-window button {
  padding: 4px 8px;
  border: none;
  background-color: #f5f5f5;
  cursor: pointer;
}

.component-window button:hover {
  background-color: #e0e0e0;
}

#search-input {
  width: 100%;
}

#search-result-panel {
  margin-top: -1px;
  width: 50%;
  display: none;
  position: absolute; /* 修改为绝对定位 */
  top: 80px; /* 根据输入框高度等情况调整合适的top值，让下拉框显示在合适位置 */
  left: 0;
  background-color: white;
  border: 1px solid #ccc;
  border-top: none;
  border-radius: 0 0 4px 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  max-height: 350px;
  overflow-y: auto;
  z-index: 2; /* 设置较高的z-index值，使其覆盖在地图之上 */
}

#container {
  margin-top: 25px;
  height: 70vh;
  position: absolute;
  z-index: 1; /* 地图容器的z-index值相对小一点，使其处于下层 */
}

/* 添加新的样式 */
.search-container {
    position: relative;
    margin-bottom: 16px;
}

.search-history {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: white;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    max-height: 200px;
    overflow-y: auto;
    z-index: 2000;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.history-item {
    padding: 8px 12px;
    cursor: pointer;
    transition: background-color 0.3s;
}

.history-item:hover {
    background-color: #f5f7fa;
}

.no-results {
    padding: 8px 12px;
    color: #909399;
    text-align: center;
}
</style>